import { createRouter, createWebHashHistory} from 'vue-router';
import { ElMessage } from 'element-plus';

const publicRoutes = [
  {
    path: '/',   
    name: 'login',
    component: () => import('../pages/login.vue'),
  }
]

export const asyncRoutes = [
  {
    path: '/admin',   
    component: () => import('../pages/adminLayoutView.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../components/admin/room.vue')
      },
      {
        path: 'customer', // 相对路径，不加/
        name: 'customer',
        component: () => import('../components/admin/customer.vue')
      },
      {
        path: 'reservation',
        name: 'reservation',
        component: () => import('../components/admin/reservation.vue')
      },
      {
        path: 'addRoom',
        name: 'addRoom',
        component: () => import('../pages/addRoom.vue')
      }
    ]
  },
  {
    path: '/user',
    component: () => import('../pages/userLayoutView.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/user/userHome' // 重定向 防止子路由相同产生冲突
      },
      {
        path: 'userHome',
        name: 'userHome',
        component: () => import('../components/user/room.vue')
      },
      {
        path: 'userReservation',
        name: 'userReservation',
        component: () => import('../components/user/reservation.vue')
      },
      {
        path: 'userInfo',
        name: 'userInfo',
        component: () => import('../components/user/info.vue')
      },
      {
        path: 'userUpdate',
        name: 'userUpdate',
        component: () => import('../pages/userUpdate.vue')
      },
      {
        path: 'userReserve',
        name: 'userReserve',
        component: () => import('../pages/userReserve.vue')
      }
    ]
  },

]


const router = createRouter({
    routes: [
      ...publicRoutes,
      ...asyncRoutes
    ],
    history: createWebHashHistory()
})
  
// 路由守卫
router.beforeEach((to, from, next) => {
// next()
  const isLoggedIn = localStorage.getItem('admin') !== null;
  
  if (to.meta.requiresAuth && !isLoggedIn) {
    // 如果目标路由需要身份验证但用户未登录
    ElMessage.error('请先登录');
    next('/');
  } else {
    next(); // 允许访问目标路由
  }
})
router.afterEach( (to, from) => {
})

export default router;